<?php
/**
 * 员工工资控制器
 */

namespace app\admin\controller;

use app\common\model\Department;
use app\common\model\Insure;
use app\common\model\Staff;
use think\Request;
use app\common\model\BasicSalary;

use app\common\validate\BasicSalaryValidate;

class BasicSalaryController extends Controller
{

    //列表
    public function index(Request $request, BasicSalary $basicSalary)
    {
        $param = $request->param();
        $where = [];
        if (isset($param['staff_id']) && $param['staff_id'] != ''){
            $where['id']=$param['staff_id'];
        }
        if (isset($param['department_id']) && $param['department_id'] != '') {
            $where['department_id']=$param['department_id'];
        }
        $order = $param['_order'] ?? '';
        $by    = $param['_by'] ?? '';
        $model = $basicSalary->hasWhere('staff',$where)->with(['staff'=>function($query){
            $query->with(['department','insure']);
        }])->order($order ?: '', $by ?: '')->order('department_id','DESC');
//        $data = $model->fetchSql(true)->select();
//        dump($data);die;
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['ID', '姓名', '部门', '入职时间', '保险种类', '基本工资', '管理工资', '职称津贴', '学历津贴', '夜班津贴', '薪级工资', '保密工资', '加班工资', '全勤奖', '通讯补助', '住房补贴', '其他补贴', '固定工资合计', '绩效工资基数','备注', '社保工资', '扣除社保', '计税工资', '个人所得税', '税后险后工资', '附件', '是否启用', '更新时间'];
            $body = [];
            $data = $model->select();
            foreach ($data as $item) {
                $record = [];
                $record['id'] = $item->id;
                $record['staff_name'] = $item->staff->name;
                $record['department_name'] = $item->staff->department->name;
                $record['hired_date'] = $item->staff->hired_date;
                $record['insurance'] = $item->staff->insure->insure;
                $record['basic_salary'] = $item->basic_salary;
                $record['manage_salary'] = $item->manage_salary;
                $record['title_salary'] = $item->title_salary;
                $record['education_salary'] = $item->education_salary;
                $record['nightwork_salary'] = $item->nightwork_salary;
                $record['payscale_salary'] = $item->payscale_salary;
                $record['secret_salary'] = $item->secret_salary;
                $record['overtime_salary'] = $item->overtime_salary;
                $record['fulltime_salary'] = $item->fulltime_salary;
                $record['phone_salary'] = $item->phone_salary;
                $record['housing_salary'] = $item->housing_salary;
                $record['other_salary'] = $item->other_salary;
                $record['total_fixed_salary'] = $item->total_fixed_salary;
                $record['base_merit_salary'] = $item->base_merit_salary;
                $record['remarks'] = $item->remarks;
                $record['social_security_salary'] = $item->social_security_salary;
                $record['deduct_social_money'] = $item->deduct_social_money;
                $record['taxable_salary'] = $item->taxable_salary;
                $record['personal_tax'] = $item->personal_tax;
                $record['after_tax_insurance_salary'] = $item->after_tax_insurance_salary;
                $files = $item->file;
                if ($files){
                    foreach ($files as $k => &$v){
                        $files[$k] = $_SERVER['SERVER_NAME'].$v;
                    }
                    $record['file'] = json_encode($files,JSON_UNESCAPED_UNICODE);
                }else{
                    $record['file'] = '无';
                }
                $record['status'] = $item->status_text;
                $record['update_time'] = $item->update_time;

                $body[] = $record;
            }
            return $this->exportData($header, $body, 'basic_salary-' . date('Y-m-d-H-i-s'));
        }
        $data = $model->paginate($this->admin['per_page'], false, ['query' => $request->get()]);
        if (isset($param['department_id']) && !empty($param['department_id'] && Department::get($param['department_id']))) {

            $this->assign('department_list', $this->getSelectList(Department::get($param['department_id']), $param['department_id']));
        } else {
            $this->assign('department_list', $this->getSelectList(new Department));
        }
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'staff_list' => Staff::all(),
            'data' => $data,
            'page' => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, BasicSalary $model, BasicSalaryValidate $validate)
    {
        if ($request->isPost()) {
            $param = $request->param();
            $staff_id = $param['staff_id'];
            $insures = Staff::where('id',$staff_id)->field('insure_id')->find()->toArray();

           $param = array_merge($param,$insures);
            //计算固定工资合计
            $baseArr = ['basic_salary','manage_salary','title_salary','education_salary','nightwork_salary','payscale_salary','secret_salary','overtime_salary','fulltime_salary','phone_salary','housing_salary','other_salary','base_merit_salary'];
            $param['total_fixed_salary'] = 0;
            foreach ($param as $key => $value){
                if ($value && in_array($key,$baseArr)){
                    $param['total_fixed_salary'] +=$value;
                }
            }
            //计算计税工资个税问题税后险后工资问题
            if ($param['social_security_salary'] != ''){
                $param['taxable_salary'] = round(floatval($param['social_security_salary'])-floatval($param['deduct_social_money']),2);
                $param['personal_tax'] = getPersonalIncomeTax(floatval($param['social_security_salary']),floatval($param['deduct_social_money']));
                $param['after_tax_insurance_salary'] = round(floatval($param['social_security_salary'])-floatval($param['deduct_social_money'])-floatval($param['personal_tax']),2);
            }

            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理附件上传
            if ($_FILES['file']['name'][0] !='') {
                $attachment_file = new \app\common\model\Attachment;
                $file = $attachment_file->uploadMulti('file');
                if ($file) {
                    $param['file'] = $file;
                } else {
                    return error($attachment_file->getError());
                }
            }
            $result = $model::create($param);

            $url = URL_BACK;
            if (isset($param['_create']) && $param['_create'] == 1) {
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功', $url) : error();
        }
        $this->assign([
            'department_list' => $this->getSelectList(new Department),
            'staff_list' => Staff::all()
        ]);

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, BasicSalary $model, BasicSalaryValidate $validate)
    {

        $data = $model::where('id', $id)->with(['staff'=>function($query){
            $query->with(['department','insure']);
        }])->find();
        if ($request->isPost()) {
            $param = $request->param();

            //计算计税工资个税问题税后险后工资问题
            //计算固定工资合计
            $baseArr = ['basic_salary','manage_salary','title_salary','education_salary','nightwork_salary','payscale_salary','secret_salary','overtime_salary','fulltime_salary','phone_salary','housing_salary','other_salary','base_merit_salary'];
            $param['total_fixed_salary'] = 0;

            foreach ($param as $key => $value){
                if ($value && in_array($key,$baseArr)){
                    $param['total_fixed_salary'] +=$value;
                }
            }

            //计算计税工资个税问题税后险后工资问题
            if ($param['social_security_salary'] != ''){
                $param['taxable_salary'] = round(floatval($param['social_security_salary'])-floatval($param['deduct_social_money']),2);
                $param['personal_tax'] = getPersonalIncomeTax(floatval($param['social_security_salary']),floatval($param['deduct_social_money']));
                $param['after_tax_insurance_salary'] = round(floatval($param['social_security_salary'])-floatval($param['deduct_social_money'])-floatval($param['personal_tax']),2);
            }
            //处理附件上传
            if (!empty($_FILES['file']['name'][0])) {
                $attachment_file = new \app\common\model\Attachment;
                $file = $attachment_file->uploadMulti('file');
                if ($file) {
                    $param['file'] = $file;
                } else {
                    return error($attachment_file->getError());
                }
            }


            $result = $data->save($param);
            return $result ? success() : error();
        }
        if ($data->staff->department){
            $this->assign(
                ['department_list' => $this->getSelectList($data->staff->department, $data->staff->department->id)]
            );
        }else{
            $this->assign([
                'department_list' => $this->getSelectList(new Department),
            ]);
        }
        $this->assign([
            'data' => $data,
            'staff_list' => Staff::all(),
        ]);

        return $this->fetch('add');

    }

    //删除
    public function del($id, BasicSalary $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //启用
    public function enable($id, BasicSalary $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 1]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }


//禁用
    public function disable($id, BasicSalary $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 0]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }
    //名字唯一
    public function nameUnique(Request $request,BasicSalary $model):bool
    {
        if ($model->where($request->param())->count()>0){
            return error('您的名称重复，请重新输入');
        }else{
            return success('细项可用');
        }
    }
}
